import {defaultFieldsConfig} from "@/views/stock/config/fieldsConfig";
import {getTableSetting, setTableConfig} from "@/api/setting";
import {deepCopy} from "@/utils";
import panelGroup from "@/views-example/dashboard/admin/components/PanelGroup.vue";
import user from "@/store/modules/user";

export default {
  data() {
    return {
      defaultFieldsConfig,
      userSelectedFields: null,
      fieldSelectDialogVisible: false,
      tableFieldsConfig: [],
      refreshTableKey: 0,
    };
  },
  computed: {

  },
  created() {

  },
  methods: {
    createTableFieldsConfig() {
      let tableFieldsConfig = [];
      if (!this.userSelectedFields) {
        // 如果为空，则选择全部
        tableFieldsConfig = this.defaultFieldsConfig;
      } else {
        this.userSelectedFields.forEach(userItem => {
          const defaultField = this.defaultFieldsConfig.find(item => item.prop === userItem.prop);
          if (defaultField) {
            const obj = deepCopy(defaultField)
            for (const userItemKey in userItem) {
              obj[userItemKey] = userItem[userItemKey]
            }
            tableFieldsConfig.push(obj);
          }
        });
      }
      this.tableFieldsConfig = tableFieldsConfig;
    },
    /**
     * 获取用户自定义字段
     * @param name
     * @returns {Promise<unknown>}
     */
    getUserFields(name) {
      return new Promise((resolve, reject) => {
        getTableSetting(name)
          .then(res => {
            this.userSelectedFields = res.data.config;
            if (!this.userSelectedFields) {
              // 如果为空，则选择全部
              this.userSelectedFields = this.defaultFieldsConfig.map(item => {
                return {
                  prop: item.prop,
                  minWidth: item.minWidth,
                }
              });
            }
            resolve(this.userSelectedFields);
          }).catch(err => {
          reject(err);
        });
      });
    },
    /**
     * 设置用户自定义字段
     * @param name
     * @param selectedFields
     * @returns {Promise<unknown>}
     */
    setUserFields(name, selectedFields) {
      return new Promise((resolve, reject) => {
        const data= {
          name: name,
          config: selectedFields
        }
        setTableConfig(data)
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      })
    }
  }
}
